/*
 * utils.js
 *
 * Copyright (C) 2006 - OS3 srl - http://www.os3.it
 *
 * Written by: Fabio Rotondo - fabio.rotondo@os3.it
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation;
 * version 2 of the License ONLY.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * NOTE: this is the GPL version of the library. If you want to include this 
 *       library inside a CLOSED SOURCE / PROPRIETARY software, you need 
 *       to purchase a COMMERCIAL LICENSE. See http://www.os3.it/license/
 *       for more info.
 */

/*
 *
 *
 */

// PUBLIC: max
liwe.utils.max = function ()
{
	if ( ! arguments.length ) return 0;

	var m = 0;
	var t;

	for ( t = 0; t < arguments.length; t ++ )
		if ( m < arguments [ t ] ) m = arguments [ t ];

	return m;
};

// PUBLIC: min
liwe.utils.min = function ()
{
	if ( ! arguments.length ) return 0;

	var m = arguments [ 0 ];
	var t;

	for ( t = 1; t < arguments.length; t ++ )
		if ( m > arguments [ t ] ) m = arguments [ t ];

	return m;
};

// PUBLIC: date2str
// Mode:
//
//	0 - YYYY MM DD	( default )
//	1 - DD MM YYYY
// 	2 - MM DD YYYY
liwe.utils.date2str = function ( date, mode )
{
	var s = new String ( date );
	var v = s.match ( new RegExp ( "([0-9]{4}).([0-9]{1,2}).([0-9]{1,2}).*" ) );

	if ( ! mode ) mode = 0;

	switch ( mode )
	{
		case 1:
			s = v [ 3 ] + "-" + v [ 2 ] + "-" + v [ 1 ];
			break;
		case 2:
			s = v [ 2 ] + "-" + v [ 3 ] + "-" + v [ 1 ];
			break;

		default:
			s = v [ 1 ] + "-" + v [ 2 ] + "-" + v [ 3 ];
	}

	return s;
};

// PUBLIC: call
// Chiama una funzione passando un array di parametri
liwe.utils.call = function ( func_name, arg_array )
{
	var i, l = arg_array.length;
	var s = "this_arg." + func_name + " ( ";
	
	for ( i = 0; i < l; i++ )
	{
		if ( i > 0 ) s += ", ";
		s += "arg_array[" + i + "]";
	}

	s += " );";

	return eval ( s );
};

// PUBLIC: word2html
// Pulisce i tag di word
liwe.utils.word2html = function ( str )
{
	var re = new RegExp ( "(<P)([^>]*>.*?)(<\/P>)", "gi" );
	var re2 = new RegExp ( "(<font|<FONT)([^*>]*>.*?)(<\/FONT>|<\/font>)", "gi" );

	var rules = [
			{ regex: /<!--[\s\S]*?-->/gi, replace_val: "" },
                        { regex: /<\\?\?xml[^>]*>/gi, replace_val: "" },
                        { regex: /<\/?\w+:[^>]*>/gi, replace_val: "" }, // e.g. <o:p...
                        { regex: /\s*Mso[-:][^;"']*/gi, replace_val: "" },
                        { regex: /\s*MSO[-:][^;"']*/gi, replace_val: "" },
                        { regex: /\s*MARGIN[-:][^;"']*/gi, replace_val: "" },
                        { regex: /\s*PAGE[-:][^;"']*/gi, replace_val: "" },
                        { regex: /\s*TAB[-:][^;"']*/gi, replace_val: "" },
                        { regex: /\s*LINE[-:][^;"']*/gi, replace_val: "" },
                        { regex: /\s*FONT-SIZE[^;"']*/gi, replace_val: "" },
                        { regex: /\s*LANG=(["'])[^"']*?\1/gi, replace_val: "" },
                        { regex: /<(P|H\d)[^>]*>([\s\S]*?)<\/\1>/gi, replace_val: "$2" },
                        { regex: /\s*\w+=(["'])((&nbsp;|\s|;)*|\s*;+[^"']*?|[^"']*?;{ 2, })\1/gi, replace_val: "" },
                        { regex: /<span[^>]*>(&nbsp;|\s)*<\/span>/gi, replace_val: "" },
                        //{ regex: /<([^\s>]+)[^>]*>(&nbsp;|\s)*<\/\1>/gi, replace_val: "" },

                        { regex: /<(\/?title|\/?meta|\/?style|\/?st\d|\/?head|\/?html|\/?body|!\[)[^>]*?>/gi, replace_val: "" },
                        { regex: /(\n(\r)?){ 2, }/gi, replace_val: "" },

			{ regex: /<o:p>\s*<\/o:p>/g, replace_val: ""},
			{ regex: /<o:p>.*?<\/o:p>/g, replace_val: "&nbsp;"},
			{ regex: /\s*mso-[^:]+:[^;"]+;?/gi, replace_val: "" },
			{ regex: /\s*MARGIN: 0cm 0cm 0pt\s*;/gi, replace_val: "" },
			{ regex: /\s*MARGIN: 0cm 0cm 0pt\s*"/gi, replace_val: "\"" },
			{ regex: /\s*TEXT-INDENT: 0cm\s*;/gi, replace_val: "" },
			{ regex: /\s*TEXT-INDENT: 0cm\s*"/gi, replace_val: "\"" },
			{ regex: /\s*TEXT-ALIGN: [^\s;]+;?"/gi, replace_val: "\"" },
			{ regex: /\s*PAGE-BREAK-BEFORE: [^\s;]+;?"/gi, replace_val: "\"" },
			{ regex: /\s*FONT-VARIANT: [^\s;]+;?"/gi, replace_val: "\"" },
			{ regex: /\s*tab-stops:[^;"]*;?/gi, replace_val: "" },
			{ regex: /\s*tab-stops:[^"]*/gi, replace_val: "" },
			{ regex: /\s*face="[^"]*"/gi, replace_val: "" },
			{ regex: /\s*face=[^ >]*/gi, replace_val: "" },
			{ regex: /\s*FONT-FAMILY:[^;"]*;?/gi, replace_val: "" },
			{ regex: /<(\w[^>]*) class=([^ |>]*)([^>]*)/gi, replace_val: "<$1$3"},
			{ regex: /<(\w[^>]*) style="([^\"]*)"([^>]*)/gi, replace_val: "<$1$3" },
			{ regex: /\s*style="\s*"/gi, replace_val: '' },
			{ regex: /<SPAN\s*[^>]*>\s*&nbsp;\s*<\/SPAN>/gi, replace_val: '&nbsp;' },
			{ regex: /<SPAN\s*[^>]*><\/SPAN>/gi, replace_val: '' },
			{ regex: /<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, replace_val: "<$1$3"},
			{ regex: /<SPAN\s*>(.*?)<\/SPAN>/gi, replace_val: '$1' },
			{ regex: /<FONT\s*>(.*?)<\/FONT>/gi, replace_val: '$1' },
			{ regex: /<\\?\?xml[^>]*>/gi, replace_val: ""},
			{ regex: /<\/?\w+:[^>]*>/gi, replace_val: ""},
			{ regex: /<H\d>\s*<\/H\d>/gi, replace_val: '' },
			{ regex: /<H1([^>]*)>/gi, replace_val: '' },
			{ regex: /<H2([^>]*)>/gi, replace_val: '' },
			{ regex: /<H3([^>]*)>/gi, replace_val: '' },
			{ regex: /<H4([^>]*)>/gi, replace_val: '' },
			{ regex: /<H5([^>]*)>/gi, replace_val: '' },
			{ regex: /<H6([^>]*)>/gi, replace_val: '' },
			{ regex: /<\/H\d>/gi, replace_val: '<br>' },
			{ regex: /<(U|I|STRIKE)>&nbsp;<\/\1>/g, replace_val: '&nbsp;' },
			{ regex: /<(B|b)>&nbsp;<\/\b|B>/g, replace_val: '' },
			{ regex: /<([^\s>]+)[^>]*>\s*<\/\1>/g, replace_val: '' },
			{ regex: /<([^\s>]+)[^>]*>\s*<\/\1>/g, replace_val: '' },
			{ regex: /<([^\s>]+)[^>]*>\s*<\/\1>/g, replace_val: '' },
			{ regex: re, replace_val: "<div$2</div>" },
			{ regex: re2, replace_val: "<div$2</div>" },
			{ regex: /size|SIZE = ([\d]{1})/g, replace_val: '' }
		];
	
	rules.iterate ( function ( reg )
                                {
                                        str = str.replace ( reg.regex, reg.replace_val );
                                        //console.debug ( reg.regex );
                                } );
	//some RegEx code for the picky browsers
	/*
	var re = new RegExp("(<P)([^>]*>.*?)(<\/P>)","gi") ;
	str = str.replace( re, "<div$2</div>" ) ;
	var re2 = new RegExp("(<font|<FONT)([^*>]*>.*?)(<\/FONT>|<\/font>)","gi") ;
	str = str.replace( re2, "<div$2</div>") ;
	str = str.replace( /size|SIZE = ([\d]{1})/g, '' ) ;
	*/
	return str ;
};

// Formats a result list iterating on the list ``lst`` and using String.formatDict with
// the three templates str_row [mandatory], str_start [optional] and str_end [optional]
// Returns the formatted string
liwe.utils.format_list = function ( lst, str_row, str_start, str_end )
{
	if ( ! lst ) return '';

	var s = new String.buffer ();
	var t, l = lst.length;

	if ( str_start ) s.add ( str_start );
	for ( t = 0; t < l; t ++ )
		s.add ( String.formatDict ( str_row, lst [ t ] ) );

	if ( str_end ) s.add ( str_end );

	return s.toString ();
};

liwe.utils._ents = null;

liwe.utils.map_entities = function ( txt )
{
	if ( ! liwe.utils_ents )
	{
		liwe.utils._ents = {
			 "&#8217;": "'",
			 "&#224;": "&agrave;",
			 "&#232;": "&egrave;",
			 "&#233;": "&eacute;",
			 "&#242;": "&ograve;",
			 "&#249;": "&ugrave;",
			 "&#8220;": '"',
			 "&#8221;": '"',
			 "&#8211;": "-",
			 "%u2013" : "-",
			 "%u2019" : "'",
	         "%u201C" : '"',
	         "%u201D" : '"'
		};

		var reg_exp = "";
		var ents = [];

		liwe.utils._ents.iterate ( function ( v, k ) { ents.push ( k ); } );
		reg_exp = "(" + "|".join ( ents ) + ")";

		liwe.utils._ents_re = RegExp ( reg_exp, "g" );
	}

	txt = txt.replace ( /&#37;/g, "%" );

	return txt.replace ( liwe.utils._ents_re, function ( k ) { return liwe.utils._ents [ k ]; } );
};

liwe.utils.rand = function ( max )
{
	return Math.floor ( Math.random() * ( max + 1 ) );
};

liwe.utils.unique_id = function ()
{
	var epoch = new Date ( 1970, 1, 1 );
	var rnd, d, t;
	var res = [];

	rnd = liwe.utils.rand ( Date.parse ( new Date () ) );

	for ( t = 0; t < 4; t ++ )
	{
		res.push ( '' + rnd );

 		rnd = liwe.utils.rand ( rnd );
		d = new Date ( rnd )

		rnd = Math.abs ( liwe.utils.rand ( d - epoch ) );
	}

	return res.join ( '-' );
};

liwe.utils.supports = function ( name )
{
	switch ( name )
	{
		case "file":
			return !! ( window.File && window.FileList && window.FileReader );
		case "storage":
			return !! ( 'localStorage' in window && window [ 'localStorage' ] !== null );
		case "placeholder":
			return ( 'placeholder' in document.createElement ( 'input' ) );

		default:
			return liwe.utils._dom_supports ( name );
	}
};

liwe.utils._dom_supports = function ( prop )
{
	var div = document.createElement ( 'div' );
	var vendors = 'Khtml Ms O Moz webkit'.split ( ' ' ), len = vendors.length;  
  
	if ( prop in div.style ) return true;
  
	prop = prop.replace ( /^[a-z]/, function ( val ) { return val.toUpperCase(); });

	while ( len-- ) if ( vendors [ len ] + prop in div.style ) return true;
		
	return false;  
};
